import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sabre_sync_fencing/dd_core/dd_http.dart';
import 'package:sabre_sync_fencing/dd_module/dd_launch_and_main/pages/dd_guide_page.dart';
import 'package:sabre_sync_fencing/dd_module/dd_launch_and_main/pages/dd_login_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../dd_core/dd_config.dart';
import '../../../dd_core/dd_other.dart';
import '../../../dd_core/dd_user_service.dart';
import '../../../dd_models/dd_oauth_model.dart';
import '../pages/dd_main_tab_page.dart';

class DDSplashController extends GetxController {
  @override
  void onInit()  {
    super.onInit();
     initRequst();
  }
  initRequst() async {
    final result = await getAppConfig();
    if (result != null && result['code'] == 0 && result["data"] != null && result["data"] != "") {
      Get.find<DDUserService>().googleKey =
          getDataByName(result['data']['items'], 'google_translation_key') ??
              '';
      Get.find<DDUserService>().rongCloudKey =
          getDataByName(result['data']['items'], 'rck') ?? '';
    }
    final prefs = await SharedPreferences.getInstance();
    final authorizationToken =
    await DDAppInfo.getInstance().getAuthorizationToken();
    if (prefs.getString(DDKey.cureenUid)!= null && authorizationToken != null) {
      await isValidTokenApi();
    } else {
      final firstUse = prefs.getString(DDKey.spKeyUserFirstUse);
      if (firstUse.dd_isNotEmpty) {
        navigator?.pushAndRemoveUntil(
          MaterialPageRoute(
            settings: RouteSettings(name: DDRoutesConfig.login),
            builder: (context) {
              return const DDLoginPage();
            },
          ),
              (route) => route == false,
        );
      } else {
        final prefs = await SharedPreferences.getInstance();
        prefs.setString(DDKey.spKeyUserFirstUse, "1");
        navigator?.pushAndRemoveUntil(
          MaterialPageRoute(
            settings: RouteSettings(name: DDRoutesConfig.guide),
            builder: (context) {
              return DDGuidePage();
            },
          ),
              (route) => route == false,
        );
      }
    }
  }

    Future<void> isValidTokenApi() async {
    Map<String, dynamic>? result = await isValidToken();
    if (result != null && result['code'] == 0) {
     await getUserInfoApi();
     await strategyResultApi();
      if (Get.find<DDUserService>().rongCloudKey.dd_isNotEmpty) {
        Map<String, dynamic>? rongCloudResult = await rongCloudToken();
        if (rongCloudResult != null && rongCloudResult['code'] == 0) {
          Get.find<DDUserService>().rongCloudToken = rongCloudResult["data"];
          //DDRongcloudService().init();
          navigator?.pushAndRemoveUntil(
            MaterialPageRoute(
              settings: RouteSettings(name: DDRoutesConfig.main),
              builder: (context) {
                return const DDMainTabPage();
              },
            ),
                (route) => route == false,
          );
        }
      } else {
        Map<String, dynamic>? configResult = await getAppConfig();
        if (configResult != null && configResult['code'] == 0) {
          Get.find<DDUserService>().googleKey =
              getDataByName(result['data'], 'google_translation_key') ?? '';
          Get.find<DDUserService>().rongCloudKey =
              getDataByName(result['data'], 'rck') ?? '';
          if (Get.find<DDUserService>().rongCloudKey.dd_isNotEmpty) {
            Map<String, dynamic>? rongCloudResult = await rongCloudToken();
            if (rongCloudResult != null && rongCloudResult['code'] == 0) {
              Get.find<DDUserService>().rongCloudToken =
              rongCloudResult["data"];
              navigator?.pushAndRemoveUntil(
                MaterialPageRoute(
                  settings: RouteSettings(name: DDRoutesConfig.main),
                  builder: (context) {
                    return const DDMainTabPage();
                  },
                ),
                    (route) => route == false,
              );
            }
          }
        } else {
          /// TODO  getAppConfig fail
          navigator?.pushAndRemoveUntil(
            MaterialPageRoute(
              settings: RouteSettings(name: DDRoutesConfig.main),
              builder: (context) {
                return const DDMainTabPage();
              },
            ),
                (route) => route == false,
          );
        }
      }
    } else {
      Get.find<DDUserService>().logout();
      navigator?.pushAndRemoveUntil(
        MaterialPageRoute(
          settings: RouteSettings(name: DDRoutesConfig.login),
          builder: (context) {
            return const DDLoginPage();
          },
        ),
        (route) => route == false,
      );
    }
  }

  Future<void> strategyResultApi() async {
    Map<String, dynamic>? strategyResult = await getStrategy();
    if (strategyResult != null && strategyResult['code'] == 0) {
      Get.find<DDUserService>().userServiceAccountId =
          strategyResult["data"]["userServiceAccountId"] ?? '';
    }
  }

  Future<void> getUserInfoApi() async {
    final prefs = await SharedPreferences.getInstance();
    String cureenUid =  await prefs.getString(DDKey.cureenUid) ?? '';
    Map<String, dynamic>? getUserInfoResult = await getUserInfo(cureenUid);
    if (getUserInfoResult != null && getUserInfoResult['code'] == 0) {
      DDUserInfoModel infoModel = DDUserInfoModel.fromJson(getUserInfoResult["data"]);
       Get.find<DDUserService>().authModel.userinfo = infoModel;
    }
  }


  @override
  void onClose() {
    super.onClose();
  }
}
